clear all
global system "linux"

if "${system}" == "linux" {
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"

*** 1. Remove files created before
cd "${code}/tba_elig"
local flist1: dir "${Estimates}" files "embs-lps-pp*.gph"
local flist2: dir "${Estimates}" files "embs-lps-pp*.ster"
foreach f in `flist1' `flist2' {
	cap erase "${Estimates}/`f'"
}
local flist: dir "${log}" files "*"
foreach f of local flist {
	cap erase "${log}/`f'"
}


*** 2. Run regressions
local cmd "sbatch -export=HOME,PATH,SHELL -a 1-7 embs-lps-prepaid.sh" 
di "`cmd'"

local JobIdFile "${log}/job-id.csv"  
log using `JobIdFile', name("jobid") text replace
shell `cmd'
log close _all

do _sbatch-job "`JobIdFile'"


*** 3. combine figures
local pp_list ""
foreach n of numlist 24(12)84 {
	local pp_list "`pp_list' ${Estimates}/embs-lps-pp`n'.gph"
}

graph combine `pp_list' 
graph export "${figure}/embs-lps-pp.pdf", replace

*** 4. Tables

clear
set obs 1
gen PaboveC = 1
gen PaboveC1 = 1
gen Cutoff = 1
gen notba = 1
gen ltvprev_diff = 1
gen HiP = 1

run _esttab-latex-options.do
qui do "${code}/_labels"

**** 1. Prepayment

eststo clear

local mtitle ""

foreach Age of numlist 24(12)84 {

	local mtitle "`mtitle' `"By Age `Age'"'"

	est use "${Estimates}/embs-lps-pp`Age'"
	
	eststo
	estadd local llpa "Y"
	estadd local Zip "Y"
	estadd local Lender "Y"
	estadd local Month "Y"
	estadd local RateBin "Y"
	estadd local control "Y"
}
	
esttab using "${table}/embs-lps-pp.tex", replace keep(HiP 1.HiP#c.PaboveC1) coeflabels(1.HiP#c.PaboveC1 "$ z_i\times 1[z_i>0]$") ///
 ${opts_esttab}  b(%9.3fc) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
 stats(llpa Zip Lender RateBin control N r2_a, fmt(%1s %1s %1s %1s %1s %1s %9.2fc) ///
 labels("LLPA FE" "Zipcode FE" "Lender FE" "Mortgage Rate X Month FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$")) ///
 mtitle(`mtitle')



